/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.tutorial.actions;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import opiam.admin.applis.tutorial.beans.Person;
import opiam.admin.applis.tutorial.forms.SearchPersonForm;
import opiam.admin.faare.SearchResult;
import opiam.admin.faare.service.services.SortService;
import opiam.admin.faare.service.services.StandardService;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.service.StrutsService;
import opiam.admin.faare.struts.utils.SessionContext;

/**
 * This class allows to search one or several person entries.
 *
 * This Action class inherits from SecureAction class.
 * The SecureAction class checks that the user is connected before calling
 * the action methods.
 */
public class SearchAction  extends SecureAction
{
    /** Instance of the log4j logger.
     * Used to generate the execution traces. */
    private static Logger _logger = Logger.getLogger(SearchAction.class);

    /**
     * This method is called to execute the action once the checks have been
     * performed by the SecureAction class.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public ActionForward secureExecute(ActionMapping mapping,
            ActionForm actionForm,
            HttpServletRequest request,
            HttpServletResponse httpServletResponse)
            throws IOException, ServletException
    {
        SessionContext sessionContext = null;
        ActionMessages msgErrors = new ActionMessages();

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();
            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);

            String sessionResultName = "searchResult";

            // Removes the "searchResult" attribute in the session.
            session.removeAttribute(sessionResultName);

            // Removes the "currentEntry" attribute in the session.
            session.removeAttribute("currentEntry");

            // Checks if at least one field is not empty.
            // Returns to the search page if all the fields are empty.
            if (((((SearchPersonForm) actionForm).getGivenName() == null) ||
                    (((SearchPersonForm) actionForm).getGivenName().trim()
                          .compareToIgnoreCase("") == 0)) &&
                    ((((SearchPersonForm) actionForm).getName() == null) ||
                    (((SearchPersonForm) actionForm).getName().trim()
                          .compareToIgnoreCase("") == 0)))
            {
                // Returns the URI corresponding to the action success
                // as defined in the action configuration in the
                // struts-config.xml.
                return (mapping.findForward("success"));
            }

            // Creates the search parameters from the "personSearch" request
            // defined in the requests_conf.xml.
            List args =
                StrutsService.getSearchArgument("personSearch",
                    actionForm, sessionContext.getUserContext());

            // Calls the StandardService to search the entries.
            SearchResult searchResult =
                StandardService.search(args, sessionContext.getUserContext());

            // writes the results number on the output defined in the
            // logger_config.properties.
            _logger.debug("***** result size = " +
                searchResult.getLResults().size());

            // If there is only one result, returns the visualization page.
            if (searchResult.getLResults().size() == 1)
            {
                // Gets the entry.
                Object loadedObj = searchResult.getLResults().get(0);

                // Sets the found entry in the session.
                Person person = (Person) loadedObj;
                // Sets the Bean in the session with the "currentEntry" name.
                // This name is used in the jsp page by the Struts tags to
                // recover the attributes values of the person entry.
                session.setAttribute("currentEntry", person);

                // Returns the URI corresponding to the action success_one
                // as defined in the action configuration in the
                // struts-config.xml.
                return (mapping.findForward("success_one"));
            }

            // Calls the SortService to sort the results list according to the
            // "name" attribute.
            SortService.sort(searchResult.getLResults(), Person.class,
                "name", sessionContext.getUserContext());
            // You can also use the search method of the StandardService class
            // which allows to sort the search results according to an
            // attributes array.

            // Sets the result of the search on the session.
            session.setAttribute(sessionResultName, searchResult);

            // Returns the URI corresponding to the action success
            // as defined in the action configuration in the struts-config.xml.
            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            // Writes the error on the standard ouput console.
            se.printStackTrace();

            // Writes the error on the output defined in the
            // logger_config.properties.
            _logger.error(se.getMessage());

            // Gets the error message from the message-resources file
            // defined in the struts-config.xml
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.service.unknown"));
            // Save the error message in the request to display it in the jsp
            // page.
            saveErrors(request, msgErrors);

            // Returns the URI corresponding to the error
            return (mapping.findForward("error"));
        }
    }
}
